package com.mall.web.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.util.WebUtils;

import com.mall.untils.Constants;
import com.mall.untils.DateUtils;
import com.mall.untils.HttpClientUtil;
import com.mall.untils.HttpGetUtil;
import com.mall.untils.MapUtil;
import com.mall.untils.RedisUtil;
import com.mall.web.service.ProgrammeService;
import com.mall.web.service.UserService;

/**
 * 方案
 *
 */
@Controller
public class ProgrammeController {
	Logger logger = LoggerFactory.getLogger(ProgrammeController.class);
	@Resource UserService userService;
	@Resource ProgrammeService programmeService;
	
	/**
     * 获取opendId之后的页面
     *
     * @return
     */
    @RequestMapping(value = "/web_programme_go")
    public ModelAndView web_index_go(HttpServletRequest request, ModelMap modelMap,HttpServletResponse response) {
        Map<String, Object> paraMap = WebUtils.getParametersStartingWith(request, "");
        String code = MapUtils.getString(paraMap, "code");
        logger.info("for trace code====>" + code);
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Constants.appid + "&secret=" + Constants.secret + "&code=" + code + "&grant_type=authorization_code";
        String res = HttpGetUtil.getStringByGet(url);
        JSONObject jsonObject = JSONObject.fromObject(res);
        String openId = (String) jsonObject.get("openid");
		return new ModelAndView(new RedirectView("web_programme?open_id="+openId));
    }
    
    @RequestMapping(value = "/web_programme")
    public String web_programme(HttpServletRequest request, ModelMap modelMap,HttpServletResponse response) {
    	Map<String, Object> paraMap = WebUtils.getParametersStartingWith(request, "");
    	String open_id = MapUtil.getStringValue(paraMap, "open_id");
    	int page_type = MapUtil.getIntValue(paraMap, "page_type");
    	modelMap.addAttribute("open_id", open_id);
		Map<String, Object> wxUserOpenId = userService.getWXUserOpenId(open_id);
		String phone = MapUtil.getStringValue(wxUserOpenId, "phone");
		if(StringUtils.isEmpty(phone)){
			return "redirect:/web_register";
		}
		modelMap.addAttribute("page_type", page_type);
		String user_type = MapUtil.getStringValue(paraMap, "user_type");
		String user_id = MapUtil.getStringValue(paraMap, "type_flag_id");
		if(StringUtils.isEmpty(user_type) || StringUtils.isEmpty(user_id)){
			user_id = MapUtil.getStringValue(wxUserOpenId, "user_id");
			user_type = MapUtil.getStringValue(wxUserOpenId, "user_type");
		}
		String skip_name="";
		List<NameValuePair> params=new ArrayList<NameValuePair>();
		Map<String, Object> map=new HashMap<String, Object>();
		modelMap.addAttribute("footNavigation", 2);
		if(user_type.equals("1")){//家长
			params.add(new BasicNameValuePair("userid",user_id ));
			
			String json_data_url ="";
			
			String programme_parent_api = RedisUtil.getRedisObject("programme_parent_api"+user_id);
			if(!StringUtils.isEmpty(programme_parent_api)){
				json_data_url=programme_parent_api;
			}else{
				json_data_url=HttpClientUtil.get(Constants.php_url+"programme_parent_api.php", params);
				RedisUtil.setRedisObject("programme_parent_api"+user_id, json_data_url);
			}
			
			JSONObject json_fromObject = JSONObject.fromObject(json_data_url);
			
			map.put("eval_total", String.valueOf(json_fromObject.get("eval_total")));
			String eval_age = String.valueOf(json_fromObject.get("eval_age"));
			JSONArray eval_age_list = JSONArray.fromObject(eval_age);
			List list = JSONArray.toList(eval_age_list);
			Collections.sort(list);
			map.put("eval_age",list);
			map.put("eval_age_new",list.get(0).toString());
			
			String programme_parent__score_api = RedisUtil.getRedisObject("programme_parent__score_api"+user_id);
			if(!StringUtils.isEmpty(programme_parent__score_api)){
				json_data_url=programme_parent__score_api;
			}else{
				json_data_url=HttpClientUtil.get(Constants.php_url+"programme_parent__score_api.php", params);
				RedisUtil.setRedisObject("programme_parent__score_api"+user_id, json_data_url);
			}
			JSONArray fromObject = JSONArray.fromObject(json_data_url);
			for (Iterator iterator = fromObject.iterator(); iterator.hasNext();) {
				JSONObject  json_object = (JSONObject) iterator.next();
				List<Map<String, Object>> news_list =new ArrayList<Map<String,Object>>();
				try {
					String min_age="37";
					String max_age="40";
					/*String month = String.valueOf(json_object.get("month"));
					if(month.contains("-")){
						String[] split = month.split("-");
						min_age=split[0];
						max_age=split[1];
					}else{
						min_age=month;
					}*/
					int direction=0;
					int fraction=0;
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					String eval_time = String.valueOf(json_object.get("eval_time"));
					Date dateStart = sdf.parse(eval_time);
					String ymd = DateUtils.getYMD();
					Date dateEnd = sdf.parse(ymd);
					int discrepantDays = DateUtils.getDiscrepantDays(dateStart, dateEnd);
					
					fraction= Integer.parseInt(String.valueOf(json_object.get("renzhi"))   );
					direction=1;
					news_list.addAll(find_news(user_id, min_age, max_age, direction,fraction, sdf, dateEnd, discrepantDays,2));
					
					fraction= Integer.parseInt(String.valueOf(json_object.get("yuyan"))    );
					direction=2;
					news_list.addAll(find_news(user_id, min_age, max_age, direction,fraction, sdf, dateEnd, discrepantDays,2));
					
					fraction= Integer.parseInt(String.valueOf(json_object.get("dayundong")));
					direction=3;
					news_list.addAll(find_news(user_id, min_age, max_age, direction,fraction, sdf, dateEnd, discrepantDays,2));
					
					fraction= Integer.parseInt(String.valueOf(json_object.get("jingxidongzuo")));
					direction=4;
					news_list.addAll(find_news(user_id, min_age, max_age, direction,fraction, sdf, dateEnd, discrepantDays,2));
					
					fraction= Integer.parseInt(String.valueOf(json_object.get("shejiao"))  );
					direction=5;
					news_list.addAll(find_news(user_id, min_age, max_age, direction,fraction, sdf, dateEnd, discrepantDays,2));
					
					fraction= Integer.parseInt(String.valueOf(json_object.get("zili"))     );
					direction=6;
					news_list.addAll(find_news(user_id, min_age, max_age, direction,fraction, sdf, dateEnd, discrepantDays,2));
					
					fraction= Integer.parseInt(String.valueOf(json_object.get("shuxue"))   );
					direction=7;
					news_list.addAll(find_news(user_id, min_age, max_age, direction,fraction, sdf, dateEnd, discrepantDays,2));
					
					fraction= Integer.parseInt(String.valueOf(json_object.get("yishu"))    );
					direction=8;
					news_list.addAll(find_news(user_id, min_age, max_age, direction,fraction, sdf, dateEnd, discrepantDays,2));
					
					String[] split = eval_time.split("-");
					json_object.put("month", split[1]);
					json_object.put("day", split[2]);
					json_object.put("list_map", news_list);
					json_object.put("min_age", min_age);
					json_object.put("max_age", max_age);
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			map.put("programme_list", fromObject);
			modelMap.addAttribute("map", map);
			skip_name="web_scheme_jz_statistics";
		}else if(user_type.equals("2")){//老师
			
			params.add(new BasicNameValuePair("tid",user_id));
			//宝宝信息
			String json_data = "";
			
			String programme_teacher_api = RedisUtil.getRedisObject("programme_teacher_api"+user_id);
			if(!StringUtils.isEmpty(programme_teacher_api)){
				json_data=programme_teacher_api;
			}else{
				json_data=HttpClientUtil.get(Constants.php_url+"programme_teacher_api.php", params);
				RedisUtil.setRedisObject("programme_teacher_api"+user_id, json_data);
			}
			
			if(json_data.equals("[]")){
				skip_name="web_scheme_ls_ability";	
				return skip_name;
			}
			JSONObject json_fromObject = JSONObject.fromObject(json_data);
			
			String[] str_arry = new String[]{"renzhi","yuyan","dayundong","jingxidongzuo","shejiao","zili","shuxue","yishu"};
			for (int i = 0; i < str_arry.length; i++) {
				Object str_obj = json_fromObject.get(str_arry[i]);
				if(null!=str_obj){
					int direction=0;
					if(str_arry[i].equals("renzhi")){
						direction=1;
					}else if(str_arry[i].equals("yuyan")){
						direction=2;
					}else if(str_arry[i].equals("dayundong")){
						direction=3;
					}else if(str_arry[i].equals("jingxidongzuo")){
						direction=4;
					}else if(str_arry[i].equals("shejiao")){
						direction=5;
					}else if(str_arry[i].equals("zili")){
						direction=6;
					}else if(str_arry[i].equals("shuxue")){
						direction=7;
					}else if(str_arry[i].equals("yishu")){
						direction=8;
					}
					JSONObject json_object = JSONObject.fromObject(str_obj.toString());
					List<Map<String, Object>> news_list =new ArrayList<Map<String,Object>>();
					try {
						String min_age="37";
						String max_age="40";
						/*String month = String.valueOf(json_object.get("month"));
						if(month.contains("-")){
							String[] split = month.split("-");
							min_age=split[0];
							max_age=split[1];
						}else{
							min_age=month;
						}*/
						int fraction=0;
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						String eval_time = String.valueOf(json_object.get("eval_time"));
						Date dateStart = sdf.parse(eval_time);
						String ymd = DateUtils.getYMD();
						Date dateEnd = sdf.parse(ymd);
						int discrepantDays = DateUtils.getDiscrepantDays(dateStart, dateEnd);
						
						JSONArray fromObject = JSONArray.fromObject(json_object.get("baby_list"));
						for (Iterator iterator = fromObject.iterator(); iterator.hasNext();) {
							JSONObject  json_object_new = (JSONObject) iterator.next();
							fraction = Integer.parseInt(json_object_new.get("score").toString());
							news_list.addAll(find_news(user_id, min_age, max_age, direction,fraction, sdf, dateEnd, discrepantDays,1));
						}
					} catch (ParseException e) {
						e.printStackTrace();
					}
					
					List<Map<String,Object>> news_list_new = new LinkedList<Map<String,Object>>();  
			        Set<Map> setMap = new HashSet<Map>();  
			        for(Map<String,Object> map1 : news_list){  
			            if(setMap.add(map1)){  
			            	news_list_new.add(map1);  
			            }  
			        }  
					
					json_object.put("list_map", news_list_new);
					map.put(str_arry[i], json_object);
				}
			}
			modelMap.addAttribute("map", map);
			skip_name="web_scheme_ls_ability";
		}else if(user_type.equals("99")){//园长
			params.add(new BasicNameValuePair("kindergarten_id",user_id));
			
			String json_data_url = "";
				json_data_url=HttpClientUtil.get(Constants.php_url+"programme_enchou_api.php", params);
			JSONArray fromObject = JSONArray.fromObject(json_data_url);
			modelMap.addAttribute("list_map", fromObject);
			skip_name="web_scheme_yz_entrance";
		}
    	return skip_name;
    }

	private List<Map<String, Object>> find_news(String user_id,
			String min_age, String max_age, int direction, int fraction,
			SimpleDateFormat sdf, Date dateEnd, int discrepantDays,int type)
			throws ParseException {
		List<Map<String, Object>> queryList = new ArrayList<Map<String,Object>>();
		Date dateStart;
		Map<String, Object> find_user_programme;
		find_user_programme = programmeService.find_user_programme(direction,fraction,min_age,max_age,user_id,type);
		/*if(null!=find_user_programme && find_user_programme.size()>0){
			String create_time = MapUtil.getStringValue(find_user_programme, "create_time");
			dateStart = sdf.parse(create_time);
			discrepantDays = DateUtils.getDiscrepantDays(dateStart, dateEnd);
			if(discrepantDays>=7){//相隔多少天
				queryList = programmeService.find_user_all_news(direction,fraction,min_age,max_age,user_id,type);
			}else{
				queryList = programmeService.find_user_all_news_history(direction,fraction,min_age,max_age,user_id,type);
			}
		}else{
			if(discrepantDays>=7){//相隔多少天
				queryList = programmeService.find_user_all_news(direction,fraction,min_age,max_age,user_id,type);
			}
		}*/
		
		if(null==find_user_programme || find_user_programme.size()==0){
			queryList = programmeService.find_user_all_news(direction,fraction,min_age,max_age,user_id,type);
		}else{
			queryList = programmeService.find_user_all_news_history(direction,fraction,min_age,max_age,user_id,type);
		}
		return queryList;
	}
	@RequestMapping(value = "/save_user_history")    
    @ResponseBody
	public String save_user_history(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		Map<String, Object> paraMap = WebUtils.getParametersStartingWith(request, "");
    	int update=programmeService.save_user_history(paraMap);
    	return String.valueOf(update);
	}
	
	
	
}
